local json = require("cjson.safe")
local ngx = ngx
local ngx_config_prefix = ngx.config.prefix
local log = require("core.log").new("template: ")

local prefix
if (type(ngx_config_prefix) == "string") then
    -- 测试框架使用
    log.error("ngx::Test使用")
    prefix = ngx_config_prefix
else
    prefix = ngx_config_prefix()
end

local home_path = prefix .. "/lua/template/"

local _M = {}
_M["tpls"] = {}

--加载模板文件
local function load_from_file(filepath)
    local key = ngx.md5(filepath);
    if not _M.tpls[key] then
        local file = io.open(filepath, "r")
        if file == nil then
            return json.encode({ ["ret"] = "error", ["msg"] = "template file not found" })
        end
        _M.tpls[key] = file:read("*all");
        file:close();
    end

    return _M.tpls[key]
end

--渲染模板
--function _M.render(self, plugin,filename,status)
function _M.render(self, msg,status)

    if status == nil then
        status = ngx.HTTP_OK
    end

    --local filepath = home_path .. plugin .. "/template/" .. filename .. ".html"
    --log.notice(filepath)
    --local content = load_from_file(filepath)
    ngx.status = status
    --ngx.header.content_type = "text/html"
    ngx.say(msg)
    ngx.exit(ngx.HTTP_OK)
end

return _M
